import React, { useState, useEffect, useMemo } from 'react'
import { useNavigate, useLocation, Outlet } from 'react-router-dom'
import { logout, getUserInfo } from '@/utils/auth';
import {
  Bell,
  Settings,
  User,
  Mail,
  ChevronDown,
  Home,
  FileText,
  Users,
  Grid3X3,
  BarChart3,
  Database,
  Shield,
  ClipboardList,
  Star,
  Trash2,
  Inbox,
  Send,
  Activity,
  Cloud,
  AlertOctagon,
  Loader2,
  CalendarClock,
  MessageCircle,
} from 'lucide-react'
import LanguageSwitcher from '@/components/LanguageSwitcher'
import ThemeSwitcher from '@/components/ThemeSwitcher'
import Breadcrumb from '@/components/Breadcrumb'
import { useTranslation } from '@/utils/i18n'
import { initTheme, useThemeStore } from '@/stores/themeStore'
import { useSystemSettingsStore } from '@/stores/systemSettingsStore'
import { useMailCenterStore } from '@/stores/mailCenterStore'
import { useNotificationStore } from '@/stores/notificationStore'
import { recordAuditLog } from '@/utils/auditLogger'
import { ROUTE_PERMISSION_MAP } from '@/config/menuPermissions'

const LEGACY_SYSTEM_NAMES = ['通用管理系统', 'Universal Management System']

const NotificationBadge = ({ count }: { count: number }) => (
  <span className="absolute -top-1 -right-1 min-w-[18px] h-4 px-1 text-[10px] flex items-center justify-center bg-gradient-to-r from-rose-500 to-orange-500 text-white rounded-full shadow-lg">
    {count > 99 ? '99+' : count}
  </span>
)

const DotBadge = ({ color = 'bg-blue-500' }: { color?: string }) => (
  <span className={`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full shadow-lg ${color}`} />
)

interface MenuItem {
  key: string
  label: string
  icon: React.ReactNode
  children?: MenuItem[]
}

interface MainLayoutProps {
  children?: React.ReactNode
}

const MainLayout: React.FC<MainLayoutProps> = ({ children }) => {
  const navigate = useNavigate()
  // 用户信息接口
  interface UserInfo {
    token?: string;
    username?: string;
    id?: string | number;
    roleKey?: string;
    permissions?: string[];
  }
  
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null)
  const [showUserMenu, setShowUserMenu] = useState(false)

  useEffect(() => {
    // 获取用户信息
    const info = getUserInfo();
    setUserInfo(info);
  }, []);

  // 处理登出
  const handleLogout = () => {
    logout();
    navigate('/login', { replace: true });
  };
  const location = useLocation()
  const { t, locale } = useTranslation()
  const { settings } = useSystemSettingsStore()
  const {
    campaigns,
    loading: campaignLoading,
    fetchCampaigns,
    lastSyncedAt: campaignSyncedAt,
  } = useMailCenterStore()
  const {
    items: notifications,
    loading: notificationLoading,
    fetchLatest,
    unreadCount,
    markAllRead,
    markAsRead,
    lastSyncedAt,
  } = useNotificationStore()
  const [newCampaignTitle, setNewCampaignTitle] = useState('新品预售内测邀约')
  const [newCampaignSegment, setNewCampaignSegment] = useState('核心会员/近 30 日消费 > 2 次')
  const [newCampaignTime, setNewCampaignTime] = useState(() => new Date(Date.now() + 3600 * 1000).toISOString().slice(0, 16))
  const [campaignFeedback, setCampaignFeedback] = useState('')
  const themePreference = useThemeStore((state) => state.theme)
  const isDark = useMemo(() => {
    if (themePreference === 'dark') return true
    if (themePreference === 'light') return false
    if (typeof window === 'undefined') return false
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }, [themePreference])
  const displaySystemName = useMemo(() => {
    const branding = settings.branding
    const fallback = (branding?.platformName || '').trim()
    const zhName = (branding?.platformNameZh || '').trim()
    const enName = (branding?.platformNameEn || '').trim()

    const candidate =
      locale === 'en-US'
        ? enName || fallback || zhName
        : zhName || fallback || enName

    if (!candidate || LEGACY_SYSTEM_NAMES.includes(candidate)) {
      return t('settings.defaultSystemName')
    }
    return candidate
  }, [settings.branding?.platformName, settings.branding?.platformNameZh, settings.branding?.platformNameEn, locale, t])
  const menuItems = useMemo<MenuItem[]>(() => [
    { key: 'dashboard', label: t('sidebar.dashboard'), icon: <Home size={16} /> },
    {
      key: 'product',
      label: t('sidebar.product'),
      icon: <Grid3X3 size={16} />,
      children: [
        { key: 'product-list', label: t('sidebar.productList'), icon: <Grid3X3 size={14} /> },
        { key: 'product-category', label: t('sidebar.productCategory'), icon: <FileText size={14} /> },
        { key: 'product-upload', label: t('sidebar.productUpload'), icon: <FileText size={14} /> },
      ],
    },
    {
      key: 'order',
      label: t('sidebar.order'),
      icon: <FileText size={16} />,
      children: [
        { key: 'order-list', label: t('sidebar.orderList'), icon: <FileText size={14} /> },
        { key: 'order-refund', label: t('sidebar.orderRefund'), icon: <FileText size={14} /> },
      ],
    },
    { key: 'user', label: t('sidebar.user'), icon: <Users size={16} /> },
    {
      key: 'document',
      label: t('sidebar.document'),
      icon: <FileText size={16} />,
      children: [
        { key: 'doc-list', label: t('sidebar.docList'), icon: <FileText size={14} /> },
        { key: 'doc-collab', label: t('sidebar.docCollab'), icon: <FileText size={14} /> },
      ],
    },
    {
      key: 'statistics',
      label: t('sidebar.statistics'),
      icon: <BarChart3 size={16} />,
      children: [
        { key: 'sales-stats', label: t('sidebar.salesStats'), icon: <BarChart3 size={14} /> },
        { key: 'data-export', label: t('sidebar.dataExport'), icon: <FileText size={14} /> },
      ],
    },
    { key: 'chat', label: t('sidebar.chat'), icon: <MessageCircle size={16} /> },
    {
      key: 'file',
      label: t('sidebar.fileManage'),
      icon: <Database size={16} />,
      children: [
        { key: 'file-manage', label: t('sidebar.fileList'), icon: <Database size={14} /> },
        { key: 'favorites', label: t('sidebar.favorites'), icon: <Star size={14} /> },
        { key: 'recycle-bin', label: t('sidebar.recycleBin'), icon: <Trash2 size={14} /> },
      ],
    },
    {
      key: 'system',
      label: t('sidebar.system'),
      icon: <Shield size={16} />,
      children: [
        { key: 'role-manage', label: t('sidebar.roleManage'), icon: <Users size={14} /> },
        { key: 'permission-manage', label: t('sidebar.permissionManage'), icon: <Shield size={14} /> },
        { key: 'menu-manage', label: t('sidebar.menuManage'), icon: <Grid3X3 size={14} /> },
      ],
    },
    { key: 'audit-log', label: t('sidebar.auditLog'), icon: <ClipboardList size={16} /> },
    { key: 'settings', label: t('sidebar.settings'), icon: <Settings size={16} /> },
  ], [t])
  const [collapsed, setCollapsed] = useState(false)
  const [expandedKeys, setExpandedKeys] = useState<string[]>([])
  const currentPathKey = useMemo(() => {
    const key = location.pathname.replace(/^\//, '')
    return key || 'dashboard'
  }, [location.pathname])
  const [mailVisible, setMailVisible] = useState(false)
  const [notificationVisible, setNotificationVisible] = useState(false)

  const menuKeyMap = useMemo(() => {
    const map = new Map<string, { item: MenuItem; parentKey?: string }>()
    const traverse = (items: MenuItem[], parentKey?: string) => {
      items.forEach((item) => {
        map.set(item.key, { item, parentKey })
        if (item.children && item.children.length) {
          traverse(item.children, item.key)
        }
      })
    }
    traverse(menuItems)
    return map
  }, [menuItems])

  useEffect(() => {
    initTheme()
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handleThemeChange = () => {
      const store = useThemeStore.getState()
      if (store.theme === 'system') {
        initTheme()
      }
    }
    mediaQuery.addEventListener('change', handleThemeChange)
    return () => mediaQuery.removeEventListener('change', handleThemeChange)
  }, [])

  useEffect(() => {
    fetchLatest()
    fetchCampaigns()
  }, [fetchLatest, fetchCampaigns])

  const toggleExpanded = (key: string) => {
    setExpandedKeys((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]))
  }

  const handleMenuClick = (key: string) => {
    navigate(`/${key}`)
  }

  // 渲染菜单项
  const renderMenuItem = (item: MenuItem) => {
    const isExpanded = expandedKeys.includes(item.key);
    
    return (
      <div key={item.key}>
        <button
          onClick={() => {
            if (item.children) {
              toggleExpanded(item.key);
            } else {
              handleMenuClick(item.key);
            }
          }}
          className={`w-full flex items-center justify-between px-3 py-2 text-sm ${collapsed ? 'justify-center' : 'justify-between'} text-slate-300 hover:text-white hover:bg-slate-700/50`}
        >
          <div className="flex items-center">
            <span className="mr-2.5">{item.icon}</span>
            {!collapsed && <span>{item.label}</span>}
          </div>
          {!collapsed && item.children && (
            <ChevronDown 
              size={14} 
              className={`transition-transform duration-300 ${isExpanded ? 'rotate-180' : ''}`}
            />
          )}
        </button>
        
        {item.children && isExpanded && !collapsed && (
          <div className="pl-8 pr-2 py-1">
            {item.children.map(child => (
              <button
                key={child.key}
                onClick={() => handleMenuClick(child.key)}
                className="w-full flex items-center px-3 py-1.5 text-xs text-slate-300 hover:text-white hover:bg-slate-700/50"
              >
                <span className="mr-2">{child.icon}</span>
                <span>{child.label}</span>
              </button>
            ))}
          </div>
        )}
      </div>
    );
  };

  // 基于权限过滤菜单：叶子节点用 ROUTE_PERMISSION_MAP 校验；父节点仅在有可见子节点时展示
  const filteredMenuItems = useMemo<MenuItem[]>(() => {
    const rawPermissions = (userInfo as { permissions?: unknown } | null)?.permissions
    const permissions = Array.isArray(rawPermissions)
      ? rawPermissions.filter((v): v is string => typeof v === 'string')
      : []
    const hasAll = permissions.includes('*')
    const roleKey = (() => {
      if (userInfo && typeof userInfo === 'object' && 'roleKey' in userInfo) {
        return (userInfo as { roleKey?: string }).roleKey?.toLowerCase() || ''
      }
      return ''
    })()

    const filterItems = (items: MenuItem[]): MenuItem[] => {
      const result: MenuItem[] = []
      items.forEach((item) => {
        if (item.children && item.children.length) {
          const visibleChildren = filterItems(item.children)
          if (visibleChildren.length) {
            result.push({ ...item, children: visibleChildren })
          }
        } else {
          const required = ROUTE_PERMISSION_MAP[item.key]
          const allowed = hasAll || !required || permissions.includes(required)
          if (!allowed) {
            return
          }
          if (item.key === 'user' && roleKey !== 'super-admin') {
            return
          }
          result.push(item)
        }
      })
      return result
    }

    return filterItems(menuItems)
  }, [menuItems, userInfo])

  useEffect(() => {
    const menuData = menuKeyMap.get(currentPathKey)
    if (location.pathname === '/' && currentPathKey === 'dashboard') {
      return
    }
    if (menuData) {
      if (menuData.parentKey) {
        setExpandedKeys((prev) => (prev.includes(menuData.parentKey!) ? prev : [...prev, menuData.parentKey!]))
      }
      recordAuditLog({
        module: menuData.item.label,
        operationType: 'visit_page',
        resultMessage: `用户访问了 ${menuData.item.label} 菜单`,
        metadata: { requestUrl: location.pathname },
      })
    }
  }, [currentPathKey, location.pathname, menuKeyMap])

  // 兜底的排期函数，避免未实现的 store 方法导致页面崩溃
  const scheduleCampaign = React.useCallback((payload: { title: string; segment: string; scheduledAt: string; status: string; createdBy: string }) => {
    console.log('scheduleCampaign (mock):', payload)
  }, [])

  const handleScheduleCampaign = React.useCallback(() => {
    const title = newCampaignTitle.trim()
    const segment = newCampaignSegment.trim()

    if (!title) {
      setCampaignFeedback('请填写任务名称')
      return
    }

    if (!segment) {
      setCampaignFeedback('请填写目标人群')
      return
    }

    let scheduledAt = newCampaignTime
    const date = newCampaignTime ? new Date(newCampaignTime) : undefined
    if (date && !Number.isNaN(date.getTime())) {
      scheduledAt = date.toISOString()
    } else {
      scheduledAt = new Date(Date.now() + 60 * 60 * 1000).toISOString()
    }

    scheduleCampaign({
      title,
      segment,
      scheduledAt,
      status: 'scheduled',
      createdBy: userInfo?.username || '运营助手',
    })

    setCampaignFeedback('已添加到发送排期')
  }, [newCampaignSegment, newCampaignTime, newCampaignTitle, scheduleCampaign, userInfo?.username])

  const renderMailModal = () => (
    <div
      className={`fixed inset-0 z-50 transition-opacity duration-300 ${mailVisible ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}`}
    >
      <div className="absolute inset-0 bg-slate-900/50 backdrop-blur-sm" onClick={() => setMailVisible(false)} />
      <div
        className={`absolute top-20 right-20 w-[440px] bg-white dark:bg-slate-900 rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 transform transition-all duration-300 origin-top-right ${mailVisible ? 'scale-100 opacity-100' : 'scale-95 opacity-0'}`}
      >
        <div className="px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex items-center justify-between">
          <div>
            <p className="text-base font-semibold text-slate-700 dark:text-slate-200">邮件控制中心</p>
            <p className="text-xs text-slate-400">配置 SMTP · 管理营销任务 · 触达商家与会员</p>
          </div>
          <button onClick={() => setMailVisible(false)} className="text-slate-400 hover:text-slate-200 text-xl leading-none">×</button>
        </div>
        <div className="px-6 py-4 space-y-5 max-h-[460px] overflow-y-auto">
          <div className="bg-blue-50 dark:bg-blue-900/30 border border-blue-100 dark:border-blue-700 rounded-xl p-4 flex gap-3">
            <Inbox size={18} className="text-blue-500 mt-1" />
            <div>
              <p className="text-sm font-medium text-blue-700 dark:text-blue-300">{settings.branding?.customerServiceEmail || 'noreply@example.com'}</p>
              <p className="text-xs text-blue-600/80 dark:text-blue-400 mt-1">SMTP 连接正常，已开启 DKIM/SPF 签名。点击下方按钮可跳转系统设置。</p>
              <div className="flex items-center gap-2 mt-2 text-[11px] text-blue-500">
                <CalendarClock size={12} />
                最近同步：{campaignSyncedAt ? new Date(campaignSyncedAt).toLocaleString() : '—'}
              </div>
            </div>
          </div>

          <div>
            <div className="flex items-center justify-between mb-2">
              <p className="text-xs font-semibold text-slate-500 uppercase flex items-center gap-2"><Send size={14} /> 最近任务</p>
              <button onClick={fetchCampaigns} className="text-xs text-blue-500 flex items-center gap-1">
                {campaignLoading && <Loader2 size={12} className="animate-spin" />} 刷新
              </button>
            </div>
            <div className="space-y-2">
              {campaigns.map((item) => (
                <div key={item.id} className="border border-slate-200 dark:border-slate-700 rounded-xl px-4 py-3 hover:border-blue-400 hover:shadow-md transition-all">
                  <div className="flex items-center justify-between text-xs text-slate-400">
                    <span>{new Date(item.scheduledAt).toLocaleString()}</span>
                    <span>
                      {item.status === 'completed' && <span className="text-emerald-500">已完成</span>}
                      {item.status === 'running' && <span className="text-blue-500">发送中…</span>}
                      {item.status === 'scheduled' && <span className="text-orange-500">待发送</span>}
                      {item.status === 'draft' && <span className="text-slate-400">草稿</span>}
                    </span>
                  </div>
                  <p className="text-sm font-medium text-slate-700 dark:text-slate-200 mt-1">{item.title}</p>
                  <p className="text-xs text-slate-400 mt-1">目标人群：{item.segment}</p>
                  <div className="text-[11px] text-slate-400 mt-1">
                    {item.sentCount ? `已发送 ${item.sentCount} 封 · ` : ''}送达率 {item.deliverRate ? `${item.deliverRate.toFixed(1)}%` : '—'}
                  </div>
                </div>
              ))}
              {!campaigns.length && <p className="text-xs text-slate-400">暂无邮件任务，可立即创建。</p>}
            </div>
          </div>

          <div className="border border-slate-200 dark:border-slate-700 rounded-xl p-4 space-y-3">
            <p className="text-xs font-semibold text-slate-500 uppercase">快速排期</p>
            <input
              value={newCampaignTitle}
              onChange={(e) => setNewCampaignTitle(e.target.value)}
              className="w-full px-3 py-2 text-sm bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/60"
              placeholder="任务名称，例如：会员专享券提醒"
            />
            <textarea
              value={newCampaignSegment}
              onChange={(e) => setNewCampaignSegment(e.target.value)}
              rows={2}
              className="w-full px-3 py-2 text-sm bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/60"
              placeholder="目标人群"
            />
            <input
              type="datetime-local"
              value={newCampaignTime}
              onChange={(e) => setNewCampaignTime(e.target.value)}
              className="w-full px-3 py-2 text-sm bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/60"
            />
            {campaignFeedback && <p className="text-xs text-emerald-500">{campaignFeedback}</p>}
            <button
              onClick={handleScheduleCampaign}
              className="w-full px-4 py-2 text-sm bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-xl shadow hover:shadow-lg transition-all"
            >
              添加到发送排期
            </button>
          </div>
        </div>
      </div>
    </div>
  )

  const renderNotificationPanel = () => (
    <div
      className={`fixed inset-0 z-50 transition-opacity duration-300 ${notificationVisible ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}`}
    >
      <div className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm" onClick={() => setNotificationVisible(false)} />
      <div
        className={`absolute top-20 right-24 w-[360px] bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-2xl overflow-hidden transform transition-all duration-300 origin-top-right ${notificationVisible ? 'scale-100 opacity-100' : 'scale-95 opacity-0'}`}
      >
        <div className="px-5 py-4 border-b border-slate-200 dark:border-slate-700 flex items-center justify-between">
          <div>
            <p className="text-sm font-semibold text-slate-700 dark:text-slate-200">智能通知中心</p>
            <p className="text-[11px] text-slate-400">实时跟进风险、运维与物流事件</p>
          </div>
          <div className="flex items-center gap-2 text-xs">
            <button onClick={fetchLatest} className="text-blue-500 flex items-center gap-1">
              {notificationLoading && <Loader2 size={12} className="animate-spin" />} 同步
            </button>
            <button onClick={markAllRead} className="text-slate-400 hover:text-slate-200">
              全部已读
            </button>
          </div>
        </div>
        <div className="max-h-[380px] overflow-y-auto divide-y divide-slate-100 dark:divide-slate-800 text-sm">
          {notifications.map((item) => (
            <div
              key={item.id}
              className={`px-5 py-4 transition-colors ${item.read ? 'bg-transparent' : 'bg-slate-50/80 dark:bg-slate-800/50'} hover:bg-slate-50 dark:hover:bg-slate-800/70 flex gap-3`}
              onClick={() => markAsRead(item.id)}
            >
              <div className="mt-1">
                {item.category === 'risk' && <AlertOctagon size={16} className="text-rose-500" />}
                {item.category === 'ops' && <Cloud size={16} className="text-blue-500" />}
                {item.category === 'logistics' && <Activity size={16} className="text-emerald-500" />}
                {item.category === 'marketing' && <Send size={16} className="text-purple-500" />}
              </div>
              <div>
                <p className="font-medium text-slate-700 dark:text-slate-200">{item.title}</p>
                <p className="text-xs text-slate-400 mt-1">{item.message}</p>
                <p className="text-[11px] text-slate-400 mt-2">{new Date(item.createdAt).toLocaleString()}</p>
              </div>
            </div>
          ))}
          {!notifications.length && <p className="px-5 py-6 text-xs text-slate-400 text-center">暂无通知</p>}
        </div>
        <div className="px-5 py-3 text-[11px] text-slate-400 border-t border-slate-100 dark:border-slate-800">
          最近同步：{lastSyncedAt ? new Date(lastSyncedAt).toLocaleTimeString() : '—'}
        </div>
      </div>
    </div>
  )

  return (
    <div className="flex h-screen bg-gradient-to-br from-gray-50 via-white to-gray-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900">
      <div className={`bg-gradient-to-b from-slate-800 via-slate-800 to-slate-900 transition-all duration-300 ${collapsed ? 'w-16' : 'w-64'} flex-shrink-0 shadow-xl relative overflow-hidden`}>
        <div className="absolute inset-0 bg-gradient-to-br from-blue-600/10 to-purple-600/10 pointer-events-none"></div>
        <div className="h-16 flex items-center justify-center border-b border-slate-700/50 relative z-10">
          <div className="flex items-center space-x-2 px-2">
            {settings.branding?.platformLogo ? (
              <img
                src={settings.branding.platformLogo}
                alt="Logo"
                className="w-10 h-10 rounded-xl object-contain flex-shrink-0 shadow-lg transform hover:scale-105 transition-transform"
              />
            ) : (
              <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg transform hover:scale-105 transition-transform flex-shrink-0">
                <Grid3X3 size={20} className="text-white" />
              </div>
            )}
            {!collapsed && (
              <span
                className={`font-bold text-base truncate transition-colors duration-300 ${
                  isDark ? 'text-white' : 'text-slate-900'
                }`}
              >
                {displaySystemName}
              </span>
            )}
          </div>
        </div>
        <div className="flex-1 overflow-y-auto overflow-x-hidden relative z-10 scrollbar-thin scrollbar-dark">
          <nav className="py-2 pb-4">{filteredMenuItems.map((item) => renderMenuItem(item))}</nav>
        </div>
        <div className="border-t border-slate-700/50 p-3 relative z-10">
          <button
            onClick={() => setCollapsed(!collapsed)}
            className="w-full flex items-center justify-center py-2 text-slate-300 hover:text-white hover:bg-slate-700/50 rounded-lg transition-all duration-200"
          >
            <ChevronDown size={16} className={`transition-transform duration-300 ${collapsed ? 'rotate-90' : '-rotate-90'}`} />
          </button>
        </div>
      </div>

      <div className="flex-1 flex flex-col overflow-hidden">
        <header className="bg-white/80 dark:bg-gray-800/80 backdrop-blur-md shadow-sm border-b border-gray-200/50 dark:border-gray-700/50 h-16 flex items-center justify-between px-6 relative z-10">
          <div className="flex items-center space-x-4">
            <h1
              className={`text-xl font-bold transition-colors duration-300 ${
                isDark ? 'text-white' : 'text-slate-900'
              }`}
            >
              {displaySystemName}
            </h1>
          </div>

          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-2">
              <LanguageSwitcher />
              <ThemeSwitcher />
              <button
                onClick={() => {
                  setMailVisible(!mailVisible)
                  setNotificationVisible(false)
                  
                }}
                className="p-2.5 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-all duration-200 relative group dark:hover:bg-gray-700 dark:text-gray-300"
              >
                <Mail size={18} />
                {!mailVisible && <DotBadge color="bg-blue-500" />}
                <span className="absolute left-1/2 -bottom-8 -translate-x-1/2 whitespace-nowrap text-xs bg-slate-800 text-white px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity">邮件中心</span>
              </button>
              <button
                onClick={() => {
                  setNotificationVisible(!notificationVisible)
                  setMailVisible(false)
                  
                }}
                className="p-2.5 text-gray-500 hover:text-orange-600 hover:bg-orange-50 rounded-xl transition-all duration-200 relative dark:hover:bg-gray-700 dark:text-gray-300"
              >
                <Bell size={18} />
                {unreadCount > 0 && !notificationVisible ? <NotificationBadge count={unreadCount} /> : null}
              </button>
              <button
                onClick={() => {
                  navigate('/settings')
                }}
                className="p-2.5 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-xl transition-all duration-200 dark:hover:bg-gray-700 dark:text-gray-300"
              >
                <Settings size={18} />
              </button>
              {/* 用户信息和下拉菜单 */}
              <div className="relative">
                <button 
                  className="flex items-center space-x-2 px-3 py-2 text-gray-700 hover:bg-gray-100 rounded-xl transition-all duration-200 border border-gray-200 hover:border-gray-300"
                  onClick={() => setShowUserMenu(!showUserMenu)}
                >
                  <div className="w-6 h-6 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                    <User size={14} className="text-white" />
                  </div>
                  {userInfo?.username && <span className="text-sm font-medium">{userInfo.username}</span>}
                  <ChevronDown size={14} className={`text-gray-500 transition-transform duration-200 ${showUserMenu ? 'rotate-180' : ''}`} />
                </button>
                
                {showUserMenu && (
                  <div className="absolute right-0 mt-2 w-48 bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden z-50 animate-in fade-in-50 zoom-in-95">
                    <div className="p-3 border-b border-gray-100 bg-gray-50">
                      <p className="text-sm font-medium text-gray-800">{userInfo?.username || '用户名'}</p>
                      <p className="text-xs text-gray-500">{'普通用户'}</p>
                    </div>
                    <div className="py-1">
                      <button 
                        className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center space-x-2"
                        onClick={() => {
                          setShowUserMenu(false);
                          // 可以跳转到个人设置页面
                        }}
                      >
                        <Settings size={14} />
                        <span>个人设置</span>
                      </button>
                      <button 
                        className="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center space-x-2"
                        onClick={handleLogout}
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                          <polyline points="16 17 21 12 16 7"></polyline>
                          <line x1="21" y1="12" x2="9" y2="12"></line>
                        </svg>
                        <span>退出登录</span>
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </header>

        <Breadcrumb />

        <main className="flex-1 overflow-y-auto overflow-x-hidden bg-gradient-to-br from-gray-50/50 via-white to-gray-50/50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 scrollbar-thin">
          <div className="p-6 max-w-[1920px] mx-auto min-h-full dark:bg-transparent">{children || <Outlet />}</div>
        </main>
      </div>

      {renderMailModal()}
      {renderNotificationPanel()}
      
    </div>
  )
}

export default MainLayout
